import * as ECharts from "echarts";
import { useEffect, useRef, useState } from "react";

const getChartOptions = (chartOptions: ECharts.EChartsCoreOption) => {
  return {
    ...chartOptions,
    animation: true,
    animationDuration: 2000,
    animationDurationUpdate: 1500,
    animationEasing: "cubicInOut",
    animationEasingUpdate: "cubicInOut",
    animationThreshold: 5000,
    progressiveThreshold: 3000,
    progressive: 400,
    hoverLayerThreshold: 3000,
    stateAnimation: {
      duration: 3000,
      easing: "cubicOut",
    },
  } as ECharts.EChartsCoreOption;
};

export const EChart = (props: { chartOptions: ECharts.EChartsCoreOption }) => {
  const { chartOptions } = props;
  const ref = useRef<HTMLDivElement | null>(null);
  const [chart, setChart] = useState<ECharts.ECharts | null>(null);

  useEffect(() => {
    if (ref.current == null) return;
    if (chart == null) {
      setChart(ECharts.init(ref.current));
      return;
    }

    chart.setOption(getChartOptions(chartOptions), true);
  }, [chart, chartOptions]);

  return <div className="h-full w-full" ref={ref}></div>;
};
